<template>
  <div class="stats-container">
    <div class="header">
      <h2>统计查询</h2>
      <div class="time-filter">
        <span>当前模拟时间：</span>
        <el-tag type="info">{{ formattedTime }}</el-tag>
        <el-button
            type="primary"
            size="small"
            :icon="Refresh"
            style="margin-left: 10px"
            @click="reloadCurrentView"
        >
          刷新
        </el-button>
      </div>
    </div>

    <div class="filter-container">
      <!-- 时间范围选择 -->
      <el-date-picker
          v-model="statsParams.timeRange"
          :default-value="defaultTimeRange"
          :default-time="defaultTimeRange"
          :clearable="false"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :disabled-date="disableFutureDates"
          :disabled-hours="disableFutureHours"
          :disabled-minutes="disableFutureMinutes"
          :disabled-seconds="disableFutureSeconds"
          style="width: 300px; margin-right: 10px"
      />

      <!-- 新闻主题 -->
      <el-input
          v-model="statsParams.news_category1"
          placeholder="新闻主题1"
          clearable
          style="width: 100px; margin-right: 10px"
      />
      <el-input
          v-model="statsParams.news_category2"
          placeholder="新闻主题2"
          clearable
          style="width: 100px; margin-right: 10px"
      />
      <el-input
          v-model="statsParams.news_category3"
          placeholder="新闻主题3"
          clearable
          style="width: 100px; margin-right: 10px"
      />

      <!-- 标题长度范围 -->
      <el-input
          v-model="statsParams.min_headline_len"
          placeholder="最小标题长度"
          type="number"
          style="width: 120px; margin-right: 5px"
      />
      <span style="margin-right: 1px">-</span>
      <el-input
          v-model="statsParams.max_headline_len"
          placeholder="最大标题长度"
          type="number"
          style="width: 120px; margin-right: 10px"
      />

      <!-- 新闻内容长度范围 -->
      <el-input
          v-model="statsParams.min_body_len"
          placeholder="最小内容长度"
          type="number"
          style="width: 120px; margin-right: 5px"
      />
      <span style="margin-right: 1px">-</span>
      <el-input
          v-model="statsParams.max_body_len"
          placeholder="最大内容长度"
          type="number"
          style="width: 120px; margin-right: 10px"
      />

      <!-- 用户选择 -->
      <el-input
          v-model="statsParams.user_id"
          placeholder="用户ID"
          clearable
          style="width: 120px; margin-right: 10px"
      />

      <el-button type="primary" @click="fetchStatsData">查询</el-button>
      <el-button @click="resetStatsFilter">重置</el-button>
    </div>

    <!-- 统计结果展示 -->
    <div class="stats-result">
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-title">总新闻数量</div>
              <div class="stat-value">{{ statsData.summary.total_news || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-title">平均查看时间</div>
              <div class="stat-value">{{ statsData.summary.avg_dwelltime || 0 }}ms</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-title">总点击次数</div>
              <div class="stat-value">{{ statsData.summary.total_exposures || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div class="stat-card">
              <div class="stat-title">新闻主题数量</div>
              <div class="stat-value">{{ statsData.summary.category_count || 0 }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表展示 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover">
            <div class="chart-container">
              <div class="chart-title">平均查看时间分布</div>
              <div ref="dwellTimeChart" style="height: 300px;"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <div class="chart-container">
              <div class="chart-title">新闻主题热度</div>
              <div ref="topicHeatChart" style="height: 300px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细数据表格 -->
      <el-card shadow="hover" style="margin-top: 20px">
        <div class="table-title">详细数据</div>
        <el-table
            :data="statsData.by_category"
            style="width: 100%"
            border
            stripe
            v-loading="loading"
            height="400"
        >
          <el-table-column
              prop="category"
              label="新闻分类"
              show-overflow-tooltip
          />
          <el-table-column
              prop="news_count"
              label="新闻数量"
              align="center"
              sortable
          />
          <el-table-column
              prop="avg_headline_length"
              label="平均标题长度"
              align="center"
              sortable
          />
          <el-table-column
              prop="avg_body_length"
              label="平均内容长度"
              align="center"
              sortable
          />
          <el-table-column
              prop="exposure_count"
              label="点击量"
              align="center"
              sortable
          />
          <el-table-column
              prop="avg_dwelltime"
              label="平均查看时间(ms)"
              align="center"
              sortable
          />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, onUnmounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { useSimulationStore } from '@/store/simulation'
import { storeToRefs } from "pinia"
import * as echarts from 'echarts'
import axios from "axios";
import {ElMessage} from "element-plus";

const simulationStore = useSimulationStore()

// 从store获取模拟时间
const { formattedTime,initialTime,currentTime } = storeToRefs(simulationStore)
const { formatDateTime } = simulationStore
// 统计参数
const statsParams = ref({
  timeRange: [
    initialTime.value,
    currentTime.value,
  ],
  news_category1: '',
  news_category2: '',
  news_category3: '',
  min_headline_len: '',
  max_headline_len: '',
  min_body_len: '',
  max_body_len: '',
  user_id: ''
})

// 统计结果数据
const statsData = ref({
  by_category: [],
  summary: {
    avg_dwelltime: 0,
    category_count: 0,
    total_exposures: 0,
    total_news: 0,
    user_count: 0
  }
})



// 图表引用
const dwellTimeChart = ref(null)
const topicHeatChart = ref(null)
let dwellTimeChartInstance: echarts.ECharts | null = null
let topicHeatChartInstance: echarts.ECharts | null = null

// 加载状态
const loading = ref(false)

// 获取统计数据
const fetchStatsData = async () => {
  loading.value = true
  try {
    // 构造请求参数
    const params = {
      start_time: formatDateTime(statsParams.value.timeRange?.  [0]) || '',
      end_time: formatDateTime(statsParams.value.timeRange?.  [1]) || '',
      news_category1: statsParams.value.news_category1,
      news_category2: statsParams.value.news_category2,
      news_category3: statsParams.value.news_category3,
      min_headline_len: statsParams.value.min_headline_len,
      max_headline_len: statsParams.value.max_headline_len,
      min_body_len: statsParams.value.min_body_len,
      max_body_len: statsParams.value.max_body_len,
      user_id: statsParams.value.user_id
    }
    console.log(params)

    const res = await axios.get('http://localhost:5000/get_news_stats', { params })
    if (res.data.status !== 'success') {
      ElMessage.error(res.data.message || '获取数据失败')
      return
    }
    if(!res.data.data.summary.total_exposures){
      ElMessage.warning("未查询到相关信息!")
      statsData.value = {
        by_category: [],
        summary: {
          avg_dwelltime: 0,
          category_count: 0,
          total_exposures: 0,
          total_news: 0,
          user_count: 0
        }
      }
      clearCharts() // 清空图表
      return
    }

    statsData.value = res.data.data

    // 更新图表
    await nextTick(() => {
      updateCharts()
    })

  } catch (error) {
    console.error('获取统计数据失败:', error)
    clearCharts() // 清空图表
  } finally {
    loading.value = false
  }
}

// 清空图表数据
const clearCharts = () => {
  if (dwellTimeChartInstance) {
    dwellTimeChartInstance.clear()
  }
  if (topicHeatChartInstance) {
    topicHeatChartInstance.clear()
  }
}

const updateCharts = () => {
  if (!dwellTimeChartInstance && dwellTimeChart.value) {
    dwellTimeChartInstance = echarts.init(dwellTimeChart.value)
  }
  if (!topicHeatChartInstance && topicHeatChart.value) {
    topicHeatChartInstance = echarts.init(topicHeatChart.value)
  }

  // 检查是否有数据
  const hasData = statsData.value.by_category && statsData.value.by_category.length > 0

  // 平均查看时间分布图表
  if (dwellTimeChartInstance) {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: hasData ? statsData.value.by_category.map((item:any) => item.category) : []
      },
      yAxis: {
        type: 'value',
        name: '平均查看时间(ms)'
      },
      series: [
        {
          name: '平均查看时间',
          type: 'bar',
          data: hasData ? statsData.value.by_category.map((item:any) => item.avg_dwelltime) : []
        }
      ],
      graphic: hasData ? undefined : {
        type: 'text',
        left: 'center',
        top: 'middle',
        style: {
          text: '暂无数据',
          fill: '#999',
          fontSize: 16
        }
      }
    }
    dwellTimeChartInstance.setOption(option)
  }

  // 主题热度图表
  if (topicHeatChartInstance) {
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center',
        data: hasData ? statsData.value.by_category.map((item:any) => item.category) : []
      },
      series: [
        {
          name: '主题热度',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: hasData ? statsData.value.by_category.map((item:any) => ({
            name: item.category,
            value: item.exposure_count
          })) : [],
          graphic: hasData ? undefined : {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无数据',
              fill: '#999',
              fontSize: 16
            }
          }
        }
      ]
    }
    topicHeatChartInstance.setOption(option)
  }
}

// 重置统计筛选
const resetStatsFilter = () => {
  statsParams.value = {
    timeRange: [
        initialTime.value,
        currentTime.value
    ],
    news_category1: '',
    news_category2: '',
    news_category3: '',
    min_headline_len: '',
    max_headline_len: '',
    min_body_len: '',
    max_body_len: '',
    user_id: ''
  }
  fetchStatsData()
}

// 默认时间范围
const defaultTimeRange = ref([
  initialTime.value,
  currentTime.value
])
// 时间规则
const disableFutureDates = (time: Date) => {
  return time > currentTime.value || time < initialTime.value
}
const disableFutureHours = () => {
  const now = currentTime.value
  return Array.from({length: 24}, (_, i) => i)
      .filter(h => h > now.getHours())
}
const disableFutureMinutes = (selectedHour: number) => {
  const now = currentTime.value
  if (selectedHour > now.getHours()) {
    return Array.from({length: 60}, (_, i) => i)
  }
  return Array.from({length: 60}, (_, i) => i)
      .filter(m => m > now.getMinutes())
}
const disableFutureSeconds = (selectedHour: number, selectedMinute: number) => {
  const now = currentTime.value
  if (selectedHour > now.getHours() ||
      (selectedHour === now.getHours() && selectedMinute > now.getMinutes())) {
    return Array.from({length: 60}, (_, i) => i)
  }
  return Array.from({length: 60}, (_, i) => i)
      .filter(s => s > now.getSeconds())
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  if (dwellTimeChartInstance) {
    dwellTimeChartInstance.resize()
  }
  if (topicHeatChartInstance) {
    topicHeatChartInstance.resize()
  }
}

const reloadCurrentView = ()=>{
  resetStatsFilter()
}

onMounted(() => {
  console.log("aaaa")
  fetchStatsData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (dwellTimeChartInstance) {
    dwellTimeChartInstance.dispose()
  }
  if (topicHeatChartInstance) {
    topicHeatChartInstance.dispose()
  }
})
</script>

<style scoped>
.stats-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.time-filter {
  display: flex;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.stat-card {
  padding: 20px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-container {
  padding: 10px;
}

.chart-title {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-left: 10px;
}
</style>